import { getToken } from "../utils/auth";

/**
 * WeChat状态管理混入
 * 管理WeChat组件的共享状态和计算属性
 */
export default {
  data() {
    return {
      // 弹窗状态
      dialogVisibleownDynamics: false,
      dialogVisibleVoice: false,
      dialogVisibleVideo: false,
      dialogVisibleDynamic: false,
      dynamicViewShow: false,
      showSettingsDialog: false,
      showTransferDialog: false,
      postNewsShow: false,
      precisionSearchView: false,
      buildGroupChat: false,
      
      // 动画和UI状态
      animation: true,
      chatFlag: true,
      friendFlag: true,
      confirmTransferBtnLoading: false,
      
      // 定时器
      videoCountdownTimer: null,
      voiceCountdownTimer: null,
      
      // 搜索和显示状态
      showSwitching: "0",
      name: null,
      
      // 当前选中项和详情ID
      item: {
        friendshipId: null,
        remark: null,
      },
      friendDetailId: null,
      groupDetailId: null,
      
      // 加载状态
      loadingMore: false,
      loadFlag: true,
      total: 0,
      
      // 群组成员列表
      groupMemberList: [],
      
      // 工具栏选择状态
      select: 1,
      
      // WebSocket消息对象
      sendMessage: {
        action: 0,
        token: getToken(),
        receiverId: "",
        content: "",
        extend: 1,
      },
      
      // 在线状态
      isOnline: true,
    };
  },
  
  computed: {
    // 当前聊天信息
    currentChat() {
      return this.$store.getters['chat/currentChat'];
    },
    
    // 是否正在搜索
    isSearching() {
      return this.$store.getters['chatList/isSearching'];
    },
    
    // 聊天列表数据
    chatList() {
      return this.$store.getters['chatList/filteredList'];
    },
    
    // 用户头像
    userAvatar() {
      return this.$store.getters?.userLogin?.avatar;
    },
    
    // 是否显示搜索框
    showSearchInput() {
      return this.select !== 2;
    },
    
    // 当前工具栏选择状态
    currentToolbarSelect() {
      return this.$store.getters.toolbarSelect;
    },
    
    // 是否正在初始化
    isInitializing() {
      return this.$store.getters.isInitializing;
    }
  },
  
  methods: {
    // 安全的ref调用方法
    safeRefCall(refName, methodName, ...args) {
      if (this.$refs[refName] && this.$refs[refName][methodName]) {
        return this.$refs[refName][methodName](...args);
      }
      console.warn(`Ref ${refName} or method ${methodName} not found`);
      return null;
    },
    
    // 更新工具栏选择状态
    updateToolbarSelect(select) {
      this.select = select;
      this.$store.commit("updateToolbarSelectState", this.select);
    },
    
    // 设置当前聊天项
    setCurrentItem(item) {
      this.item = item;
      this.$store.dispatch("chat/setCurrentChat", this.item);
    },
    
    // 清理定时器
    clearVideoTimer() {
      if (this.videoCountdownTimer !== null) {
        clearTimeout(this.videoCountdownTimer);
        this.videoCountdownTimer = null;
      }
    },
    
    clearVoiceTimer() {
      if (this.voiceCountdownTimer !== null) {
        clearTimeout(this.voiceCountdownTimer);
        this.voiceCountdownTimer = null;
      }
    },
    
    // 初始化容器状态
    initContainer() {
      this.item = {
        friendshipId: null,
        remark: null,
      };
    },
    
    // 初始化好友详情ID
    initFriendDetailId() {
      this.friendDetailId = null;
    },
    
    // 初始化群组详情ID
    initGroupDetailId() {
      this.groupDetailId = null;
    },
    
    // 初始化好友关系ID
    initFriendshipId() {
      if (this.select === 1) {
        this.friendFlag = false;
        this.$nextTick(() => {
          this.friendFlag = true;
        });
        this.item.friendshipId = null;
      } else {
        this.chatFlag = false;
        this.$nextTick(() => {
          this.chatFlag = true;
        });
        this.friendDetailId = null;
      }
    },
    
    // 检查缓存数据是否有效
    checkCachedData() {
      const cacheKeys = ['chatList_cache', 'contactList_cache', 'groupList_cache'];
      let hasValidCache = true;
      
      for (const key of cacheKeys) {
        const cachedData = localStorage.getItem(key);
        if (!cachedData) {
          hasValidCache = false;
          break;
        }
        
        try {
          const { timestamp } = JSON.parse(cachedData);
          if (Date.now() - timestamp >= 5 * 60 * 1000) {
            hasValidCache = false;
            break;
          }
        } catch (error) {
          hasValidCache = false;
          break;
        }
      }
      
      return hasValidCache;
    },
    
    // 将缓存数据加载到store中
    async loadCachedDataToStore() {
      try {
        // 加载聊天列表缓存
        const chatListCache = localStorage.getItem('chatList_cache');
        if (chatListCache) {
          const { data } = JSON.parse(chatListCache);
          this.$store.commit('chatList/SET_LIST', data);
        }
        
        // 加载联系人列表缓存
        const contactListCache = localStorage.getItem('contactList_cache');
        if (contactListCache) {
          const { data } = JSON.parse(contactListCache);
          this.$store.commit('contactList/SET_FRIENDS', data.friends || []);
          this.$store.commit('contactList/SET_GROUPS', data.groups || []);
        }
        
        // 加载群组列表缓存
        const groupListCache = localStorage.getItem('groupList_cache');
        if (groupListCache) {
          const { data } = JSON.parse(groupListCache);
          this.$store.commit('groupList/SET_LIST', data);
        }
        
      } catch (error) {
        console.error("加载缓存数据到store失败:", error);
        // 如果缓存加载失败，重新初始化
        await this.$store.dispatch("chatList/initialize");
        await this.$store.dispatch("contactList/initialize");
        await this.$store.dispatch("groupList/initialize");
      }
    },
    
    // 确保联系人数据已加载
    async ensureContactDataLoaded() {
      const friends = this.$store.getters['contactList/friends'];
      const groups = this.$store.getters['contactList/groups'];
      
      // 如果联系人数据为空，尝试重新加载
      if ((!friends || friends.length === 0) && (!groups || groups.length === 0)) {
        try {
          await this.$store.dispatch("contactList/initialize");
        } catch (error) {
          console.error("重新加载联系人失败:", error);
          this.$message.warning("联系人数据加载失败，请检查网络连接或稍后重试");
        }
      }
    },
    
    // 清理过期缓存
    cleanExpiredCache() {
      const cacheKeys = ['chatList_cache', 'contactList_cache', 'groupList_cache'];
      const now = Date.now();
      const expireTime = 5 * 60 * 1000; // 5分钟
      
      cacheKeys.forEach(key => {
        try {
          const cachedData = localStorage.getItem(key);
          if (cachedData) {
            const { timestamp } = JSON.parse(cachedData);
            if (now - timestamp >= expireTime) {
              localStorage.removeItem(key);
            }
          }
        } catch (error) {
          // 缓存数据损坏，直接删除
          localStorage.removeItem(key);
        }
      });
    },
    
    // 时间格式化方法
    chatTime(time) {
      const regex = /^\d{4}-\d{2}-\d{2}$/; // 验证YYYY-MM-DD格式
      if (regex.test(time)) {
        return time;
      } else {
        var date = new Date(time.toString());
        var now = new Date(); // 获取当前时间
        var diff = now - date; // 计算时间差（毫秒）
        if (diff > 24 * 60 * 60 * 1000) {
          // 如果时间差大于一天（毫秒）
          return (
            date.getFullYear() +
            "-" +
            (date.getMonth() + 1).toString().padStart(2, "0") +
            "-" +
            date.getDate().toString().padStart(2, "0")
          ); // 返回年月日格式
        } else {
          return (
            date.getHours().toString().padStart(2, "0") +
            ":" +
            date.getMinutes().toString().padStart(2, "0")
          ); // 返回时分秒格式
        }
      }
    }
  },
  
  // 生命周期钩子
  async created() {
    this.select = this.$store.getters.toolbarSelect;

    // 防止重复初始化
    if (this.$store.getters.isInitializing) {
      console.log("WeChat 正在初始化中，跳过重复初始化");
      return;
    }

    // 初始化各个模块
    try {
      this.$store.commit("SET_INITIALIZING", true);
      console.log("WeChat 开始初始化各个模块");

      // 检查是否已有缓存数据，避免重复请求
      const hasCachedData = this.checkCachedData();
      
      if (hasCachedData) {
        // 使用缓存数据，跳过初始化
        console.log("WeChat 使用缓存数据，跳过网络请求");
        await this.loadCachedDataToStore();
      } else {
        // 没有有效缓存，开始初始化
        console.log("WeChat 没有有效缓存，开始网络请求");
        await this.$store.dispatch("chatList/initialize");
        await this.$store.dispatch("contactList/initialize");
        await this.$store.dispatch("groupList/initialize");
      }
      
      // 确保联系人数据已加载
      await this.ensureContactDataLoaded();
      console.log("WeChat 模块初始化完成");

    } catch (error) {
      console.error("WeChat 组件模块初始化失败:", error);
    } finally {
      this.$store.commit("SET_INITIALIZING", false);
      console.log("WeChat 初始化状态已重置");
    }
  },
  
  mounted() {
    // 页面刷新时清理过期缓存
    this.cleanExpiredCache();
    
    if (localStorage.getItem("showSwitching") !== null) {
      this.showSwitching = localStorage.getItem("showSwitching");
    }
  },
  
  beforeDestroy() {
    // 清理定时器
    this.clearVideoTimer();
    this.clearVoiceTimer();
    
    // 重置初始化状态
    this.$store.commit("SET_INITIALIZING", false);
  }
};
